<template>
  <div>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header">
        <span class="title webfont-Medium">{{ title }}</span>
        <el-tooltip
          class="item"
          effect="dark"
          :content="contentTitle"
          placement="top"
        >
          <i class="el-icon-warning" />
        </el-tooltip>
      </div>

      <div class="box-main">
        <countTo
          v-if="title == '点击率' || title == '转化率'"
          :start-val="0"
          :end-val="currentPeriod * 100"
          :duration="1500"
          class="main-num"
          :suffix="suffix"
          :decimals="2"
        />

        <template v-else>
          <countTo
            v-if="title !== '展示' && title !== '点击' && title !== '安装'"
            :start-val="0"
            :end-val="currentPeriod"
            :decimals="2"
            :duration="1500"
            class="main-num"
            :prefix="unit === 'USD' ? '$' : '￥'"
          />

          <countTo
            v-else
            :start-val="0"
            :end-val="currentPeriod"
            :decimals="0"
            :duration="1500"
            class="main-num"
          />
        </template>

        <div :id="idName" class="card-chart" @click="showDetailTime" />
      </div>
      <div class="box-footer">
        <div class="ring">
          <p
            v-if="title === '展示' || title == '点击' || title == '安装'"
            class="total"
          >
            <el-tooltip
              class="item"
              effect="dark"
              :content="timeArr[0] + '至' + timeArr[1] + '的日均值'"
              placement="top"
            >
              <span class="pointer" style="color: #acb6c2"
                >日均{{ title }}</span
              >
            </el-tooltip>

            <strong style="color: #39444e">{{ pingJun }}</strong>
          </p>
          <p v-else class="total">
            <el-tooltip
              class="item"
              effect="dark"
              :content="'对比' + lastCycle[0] + '至' + lastCycle[1]"
              placement="top"
            >
              <span class="pointer" style="color: #acb6c2">环比</span>
            </el-tooltip>
            <strong class="">{{ ring }}%</strong>
            <i v-if="ring * 100 > 0" class="el-icon-caret-top top" />
            <i v-if="ring * 100 === 0">持平</i>
            <i v-if="ring * 100 < 0" class="el-icon-caret-bottom bottom" />
          </p>
<!-- 今日日环比 -->
          <!-- <p v-if="dayRingShow()" class="day">
            <el-tooltip
              class="item"
              effect="dark"
              :content="'昨日对比' + beforeYesterday"
              placement="top"
            >
              <span class="pointer" style="color: #acb6c2">日环比</span>
            </el-tooltip>
            <strong class="">{{ dayRing }}%</strong>
            <i v-if="dayRing * 100 < 0" class="el-icon-caret-bottom bottom" />
            <i v-if="dayRing * 100 === 0" class="">持平</i>
            <i v-if="dayRing * 100 > 0" class="el-icon-caret-top top" />
          </p> -->
          <!-- 今日日环比结束 -->
        </div>
      </div>
    </el-card>

    <el-dialog
      title="详细数据"
      :visible.sync="dialogFormVisible"
      width="950px"
      top="2vh"
      class="dialog-box"
      :close-on-click-modal="false"
    >
      <div v-loading="loading" elemetn-loading-text="数据加载中,请稍候">
        <div class="flex main-title">
          <div class="title flex" style="align-items: flex-end">
            <span style="line-height: 20px; color: #000000">{{
              diaTitle
            }}</span>
            <countTo
              v-if="title === '点击率' || title === '转化率'"
              :start-val="0"
              separator=","
              :end-val="detailNum * 100"
              :decimals="2"
              :duration="1500"
              class="main-num"
              :suffix="suffix"
            />

            <countTo
              v-else
              :start-val="0"
              separator=","
              :end-val="detailNum"
              :decimals="2"
              :duration="1500"
              class="main-num roboto-Bold"
              :suffix="suffix"
              :prefix="pre"
            />
          </div>
          <choose-time ref="chooseTimeBox" @timeChange="handleTimeChange" />
        </div>

        <charts-table
          :id-name="idName + 'info'"
          height="360px"
          :x-data="echartXData"
          :series-data="echartSeriesData"
        >
          <div slot="left">
            <el-radio-group
              v-model="queryEchart.type"
              size="small"
              @change="handleOPChange"
            >
              <el-radio-button label="DAILY">每天</el-radio-button>
              <el-radio-button label="HOURLY">每小时</el-radio-button>
            </el-radio-group>
          </div>
        </charts-table>

        <el-table
          ref="table"
          style="width: 100%"
          class="series-table"
          sortable="custom"
          :data="echartDataListCopy"
        >
          <el-table-column label="日期" width="200" sortable prop="date" />
          <el-table-column :label="title" align="right">
            <template slot-scope="scope">
              <span v-if="pre">{{ pre }}</span>

              <span v-if="scope.row[prop]">{{
                returnNum(scope.row[prop])
              }}</span>
              <span v-else>{{ returnNum(0) }}</span>
              <span v-if="suffix">{{ suffix }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div>
          <el-pagination
            :current-page="pageNum"
            :page-size="5"
            layout="total,  prev, pager, next, jumper"
            :total="echartDataList.length"
            @current-change="
              (index) => {
                pageNum = index;
              }
            "
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import countTo from "vue-count-to";
import chooseTime from "./chooseTime/index";
import chartsTable from "../components/charts-table.vue";

import { echartsOptions } from "@/settings.js";
import { getsLastPeriod, getBeforeYes, includeTime } from "@/utils/moment.js";
import { findReportCampaignTotal } from "@/api/overView.js";
import { mapGetters } from "vuex";
export default {
  components: {
    countTo,
    chooseTime,
    chartsTable,
  },
  props: {
    title: {
      // 标题名称
      default: "展示",
      type: String,
    },

    idName: {
      // echart盒子的id名
      default: "chart-card",
      type: String,
    },

    XData: {
      // 图表x轴
      type: Object,
    },
    seriesData: {
      // 图表y轴已经图表数据
      type: Object,
    },
    timeArr: {
      // 开始时间

      type: Object,
    },

    currentPeriod: {
      // 本期总和
      default: 0,
      type: Number,
    }, // 环比增长率=(本期数-上期数)/上期数*100%
    previousPeriod: {
      // 上期总和
      default: 0,
      type: Number,
    },
    yesterdayNum: {
      // 昨天的
      default: 0,
      type: Number,
    }, // 日环比增长率=(昨天-前天)/前天数*100%
    bforeYesterdayNum: {
      // 前天的平均数
      default: 0,
      type: Number,
    },
    unit: {
      type: String,
      default: function () {
        const unit = this.$store.state.user.unit;
        if (unit === "USD") {
          this.pre = "$";
        } else {
          this.pre = "￥";
        }
        return this.$store.state.user.unit;
      },
    },
  },

  computed: {
    ...mapGetters(["sidebar"]),
    opened() {
      return this.sidebar.opened;
    },

    // 分页数据
    echartDataListCopy() {
      if (this.echartDataList.length) {
        const arr = this.echartDataList.slice(
          (this.pageNum - 1) * 5,
          this.pageNum * 5
        );
        return arr;
      } else {
        return [];
      }
    },
    echartXData() {
      if (this.echartDataList.length) {
        const arr = this.echartDataList.map((item) => {
          return item.date;
        });

        return arr;
      } else {
        return [];
      }
    },

    echartSeriesData() {
      const obj = {
        name: this.diaTitle,
      };

      const arr = this.echartDataList.map((item) => {
        return item[this.prop];
      });
      obj.data = arr;

      obj.axisLabel = {
        // 判断是否要加前后符号
        formatter: "{value}",
      };
      const arr1 = [obj];
      return arr1;
    },

    ring() {
      const now = this.currentPeriod;
      const old = this.previousPeriod;

      if (old * 100 === 0) {
        if (now * 100 === 0) {
          // 如果这个周期也是0  那就是0增长
          return 0.0;
        } else {
          // 如果上个周期为0  这个周期有数据则为+100%
          return 100;
        }
      } else {
        // 如果上个周期数据不是0
        if (now * 100 === 0) {
          return (old * -100).toFixed(2);
        } else {
          const num = (now * 100 - old * 100) / (now * 100);
          return (num * 100).toFixed(2);
        }
      }
    },
    dayRing() {
      const now = this.yesterdayNum;
      const old = this.bforeYesterdayNum;
      if (old * 100 === 0) {
        if (now * 100 === 0) {
          // 如果这个周期也是0  那就是0增长
          return 0.0;
        } else {
          // 如果上个周期为0  这个周期有数据则为+100%
          return 100;
        }
      } else {
        // 如果上周期数据不是0,这个周期是0那就是负增长
        if (now * 100 === 0) {
          return (old * -100).toFixed(2);
        } else {
          const num = (now * 100 - old * 100) / (now * 100);
          return (num * 100).toFixed(2);
        }
      }
    },

    pingJun() {
      // 计算平均数
      const now = this.currentPeriod;
      if (this.XData.length) {
        if (this.XData[0].length > 10) {
          return (
            (this.currentPeriod * 100) /
            this.XData.length /
            100 /
            24
          ).toFixed(2);
        } else {
          return ((this.currentPeriod * 100) / this.XData.length / 100).toFixed(
            2
          );
        }
      } else {
        return 0.0;
      }
    },

    // 上个周期的值
    lastCycle() {
      const that = this;
      if (this.timeArr.length) {
        return getsLastPeriod(this.timeArr);
      }
    },
    beforeYesterday() {
      return getBeforeYes();
    },
  },
  watch: {
    opened() {
      if (this.cardChart) {
        const that = this;
        this.$nextTick(() => {
          setTimeout(() => {
            that.cardChart.resize();
          }, 200);
        });
      }
    },
    seriesData: {
      deep: true,
      handler: function (newV, oldv) {
        if (this.$route.query.uuid) {
          this.setSeriesData();
          this.createCharts();
        }
      },
    },
  },
  data() {
    return {
      loading: true,
      dialogFormVisible: false,
      cardChart: undefined,
      seriesDataInfo: [],
      detailNum: 0.0,
      pre: undefined, // 前缀
      suffix: undefined, // 后缀
      contentTitle: "", // 提示文字
      option: {
        xAxis: {
          type: "category",
          boundaryGap: false,
          show: false,
          data: [], // x轴的数据
        },
        yAxis: {
          type: "value",
          show: false,
          boundaryGap: false,
        },
        grid: {
          top: "0px",
          left: "0px",
          right: "0px",
          bottom: "0px",
        },
        series: [
          {
            data: [], // 图表数据
            type: "line",
            lineStyle: {
              color: "#24BEBE",
              width: 1,
            }, // 线条的样式
            itemStyle: {
              color: "#24BEBE",
              opacity: 0, // 为0不会绘制图形拐点消失
            },
            smooth: true,
            areaStyle: {
              color: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "rgb(36, 190,190, 1)", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "rgb(36, 190,190, 0) ", // 100% 处的颜色
                  },
                ],
                global: false, // 缺省为 false
              },
            },
          },
        ],
      },
      queryEchart: {
        campaignId: "", // 如果不是单个campaign就不填
        country: "",
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        endTime: "", // 开始时间
        startTime: "", // 结束时间
        name: "", // 查询时的名称  模糊查询
        status: "", // 状态
        userId: this.$store.state.user.userInfo.userId,
        adChannelType: "", // 投放位置
        orgId: this.$route.query.orgId || "", // 如果是自助投放为空
        uuid: this.$route.query.uuid || "",
        aId: this.$route.query.aId || this.$route.query.aid || "",
        currencyType: this.$store.state.user.unit,
        type: "DAILY", // 每天：'DAILY' 每小时'HOURLY'
        audienceType: "countryOrRegion",
        typeValue: "",
      },
      prop: undefined,
      pageNum: 1,
      echartDataList: [],
    };
  },

  mounted() {
    if (this.$route.query.uuid) {
      this.setSeriesData();
      this.createCharts();
    }
  },
  beforeDestroy() {
    window.removeEventListener("resize", () => {});
  },
  methods: {
    returnNum(num) {
      if (
        ["impressions", "taps", "taps", "installs"].indexOf(this.prop) === -1
      ) {
        return num.toFixed(2);
      } else {
        return num;
      }
    },
    dayRingShow() {
      return includeTime(this.timeArr[1]);
    },
    showDetailTime() {
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["chooseTimeBox"].initTime();
        return console.log(this.$refs);
      });
    },
    setSeriesData() {
      let title = this.title;
      this.diaTitle = this.title;
      if (title.indexOf("CPT") !== -1) {
        title = "CPT";
        this.diaTitle = "CPT";
        this.setCPT();
      } else if (title.indexOf("CPA") !== -1) {
        title = "CPA";
        this.diaTitle = "CPA";
        this.setCPA();
      } else if (title === "点击率") {
        this.settaps();
      } else if (title === "转化率") {
        this.setttr();
      } else if (title === "安装") {
        title = "下载";
      }

      const index = echartsOptions.findIndex((item) => {
        return item.name === title;
      });
      const key = echartsOptions[index].val;
      this.prop = key;

      // 循环出来表格数据
      const arr = this.seriesData.map((item, index) => {
        return item[key];
      });
      this.seriesDataInfo = arr;

      // 计算总数

      let num = 0;
      if (
        title !== "点击率" &&
        title !== "转化率" &&
        title !== "CPT" &&
        title !== "CPA"
      ) {
        this.seriesData.forEach((item) => {
          num += item[key];
        });
        this.num = num;
        this.contentTitle = `${this.timeArr[0]}至${this.timeArr[1]}周期内${title}数总和`;
      } else {
        this.num = this.previousPeriod;
        this.contentTitle = `${this.timeArr[0]}至${this.timeArr[1]}周期内${title}`;
      }
    },

    // 計算平均每次转化费用
    setCPT() {
      const _that = this;
      let localSpendAmount = 0;
      let taps = 0;
      _that.seriesData.forEach((item) => {
        localSpendAmount += parseFloat(item.localSpendAmount);
      });
      _that.seriesData.forEach((item) => {
        taps += parseFloat(item.taps);
      });
      if (taps === 0) {
        _that.num = 0.0;
      } else {
        _that.num = isNaN((localSpendAmount / taps).toFixed(2))
          ? 0
          : (localSpendAmount / taps).toFixed(2);
      }
    },

    // 计算平均每次转化费用
    setCPA() {
      const _that = this;
      let localSpendAmount = 0;
      let installs = 0;
      _that.seriesData.forEach((item) => {
        localSpendAmount += parseFloat(item.localSpendAmount);
      });
      _that.seriesData.forEach((item) => {
        installs += parseFloat(item.installs);
      });
      if (installs === 0) {
        _that.num = 0.0;
      } else {
        _that.num = isNaN((localSpendAmount / installs).toFixed(2))
          ? 0
          : (localSpendAmount / installs).toFixed(2);
      }
    },

    // 计算点击率
    settaps() {
      this.suffix = "%";
      var taps = 0;
      var impressions = 0;
      this.seriesData.forEach((item) => {
        taps += parseFloat(item.taps);
      });
      this.seriesData.forEach((item) => {
        impressions += parseFloat(item.impressions);
      });
      this.num = isNaN((taps / impressions).toFixed(2))
        ? 0
        : ((taps / impressions) * 100).toFixed(2);
    },

    // 计算下载率
    setttr() {
      this.suffix = "%";
      var installs = 0;
      var taps = 0;
      this.seriesData.forEach((item) => {
        installs += parseFloat(item.installs);
      });
      this.seriesData.forEach((item) => {
        taps += parseFloat(item.taps);
      });

      if (installs / taps === Infinity) {
        this.num = "0.00";
      } else {
        this.num = isNaN((installs / taps).toFixed(2))
          ? 0
          : ((installs / taps) * 100).toFixed(2);
      }
    },

    createCharts() {
      const idname = this.idName;
      this.cardChart = echarts.init(document.getElementById(idname));

      this.option.xAxis.data = this.XData;
      this.option.series[0].data = this.seriesDataInfo;
      this.cardChart.setOption(this.option, true);
      this.cardChart.resize();
      const that = this;
      window.addEventListener("resize", () => {
        that.cardChart.resize();
      });
    },

    // 弹窗图表
    handleTimeChange(arr) {
      this.queryEchart.startTime = arr[0];
      this.queryEchart.endTime = arr[1];
      this.findReportCampaignTotal();
    },
    handleOPChange() {
      this.pageNum = 1;
      this.total = 0;
      this.findReportCampaignTotal();
    },

    async findReportCampaignTotal() {
      this.loading = true;
      const res = await findReportCampaignTotal(this.queryEchart);
      this.loading = false;
      if (res.data.code === 20000) {
        this.echartDataList = res.data.data.result;

        this.detailNum = res.data.data.now[this.prop];
      } else {
        this.$message.closeAll();
        this.$message.error(res.data.message || "获取数据失败，请稍后重试");
      }
    },
  },
};
</script>

<style lang="scss" scoped="true">
@import "~@/styles/variables.scss";

.box-card {
  ::v-deep.el-card__header {
    border: none !important;
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 14px;
    }

    i {
      font-size: 18px;
      border-radius: 50%;
      color: #c4c4c4;
    }
  }

  ::v-deep .el-card__body {
    padding: 16px !important;
    padding-top: 0;
  }

  ::v-deep .el-card__header {
    padding: 16px;
    padding-bottom: 8px;
  }

  .box-main {
    ::v-deep.main-num {
      color: rgba(0, 0, 0, 1);
      font-size: 24px;
      line-height: 24px;
      font-family: "Roboto-Bold", "PingFangSC-Medium", PingFangSC, sans-serif !important;
    }

    .card-chart {
      height: 58px;
      width: 100%;
    }
  }

  .box-footer {
    padding-top: 14px;
    border-top: 1px solid rgba(57, 68, 78, 0.1);

    .ring {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;

      p {
        display: flex;
        align-items: center;
      }

      span {
        color: #39444e;
        padding-right: 10px;
      }

      strong {
        padding-right: 8px;
        color: #39444e;
        font-weight: 400;
        // font-size: 12px;
      }

      .bottom {
        color: $mainColor1;
      }

      .top {
        color: #e9716a;
      }
    }
  }
}

.dialog-box {
  ::v-deep .el-dialog__header {
    border-bottom: 1px solid rgba(57, 68, 78, 0.1);
    font-family: "PingFangSC-Medium", PingFangSC, sans-serif !important;
  }

  .main-title {
    margin-top: -8px;
    margin-bottom: 24px;

    .title {
      .main-num {
        color: #000000;
        font-size: 24px;
        line-height: 24px;
        margin-left: 8px;
      }
    }
  }
}
</style>
